<template>
  <div class="status-event-panel">
    <a-card title="状态事件管理" size="small">
      <template #extra>
        <a-space>
          <a-button
            type="primary"
            size="small"
            @click="showCreateEventModal = true"
          >
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            新建事件
          </a-button>
          <a-button size="small" @click="refreshEvents">
            <template #icon>
              <IconifyIcon icon="ant-design:reload-outlined" />
            </template>
            刷新
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="statusEvents"
        :pagination="false"
        size="small"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getEventTypeColor(record.type)">
              {{ getEventTypeLabel(record.type) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getEventStatusColor(record.status)">
              {{ getEventStatusLabel(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="viewEventDetail(record)"
              >
                查看
              </a-button>
              <a-button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="executeEvent(record)"
              >
                执行
              </a-button>
              <a-popconfirm
                title="确定要删除这个事件吗？"
                @confirm="deleteEvent(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 事件详情模态框 -->
    <a-modal
      :open="showEventDetailModal"
      title="事件详情"
      width="600px"
      @cancel="showEventDetailModal = false"
    >
      <div v-if="selectedEvent" class="event-detail">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="事件ID">{{
            selectedEvent.id
          }}</a-descriptions-item>
          <a-descriptions-item label="事件类型">{{
            getEventTypeLabel(selectedEvent.type)
          }}</a-descriptions-item>
          <a-descriptions-item label="源资源ID">{{
            selectedEvent.sourceId
          }}</a-descriptions-item>
          <a-descriptions-item label="源类型">{{
            selectedEvent.sourceType
          }}</a-descriptions-item>
          <a-descriptions-item label="状态">{{
            getEventStatusLabel(selectedEvent.status)
          }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{
            formatTime(selectedEvent.timestamp)
          }}</a-descriptions-item>
          <a-descriptions-item label="关联ID">{{
            selectedEvent.correlationId || '无'
          }}</a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <h4>事件载荷</h4>
        <pre class="event-payload">{{
          JSON.stringify(selectedEvent.payload, null, 2)
        }}</pre>
      </div>
    </a-modal>

    <!-- 创建事件模态框 -->
    <a-modal
      :open="showCreateEventModal"
      title="新建状态事件"
      @ok="saveEvent"
      @cancel="showCreateEventModal = false"
    >
      <a-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventRules"
        layout="vertical"
      >
        <a-form-item label="事件类型" name="type">
          <a-select v-model:value="eventForm.type" placeholder="选择事件类型">
            <a-select-option value="STATUS_CHANGED">状态变更</a-select-option>
            <a-select-option value="LIFECYCLE_CHANGED"
              >生命周期变更</a-select-option
            >
            <a-select-option value="AVAILABILITY_CHANGED"
              >可用性变更</a-select-option
            >
            <a-select-option value="VERSION_CHANGED">版本变更</a-select-option>
            <a-select-option value="CUSTOM_STATUS_CHANGED"
              >自定义状态变更</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item label="源类型" name="sourceType">
          <a-select
            v-model:value="eventForm.sourceType"
            placeholder="选择源类型"
          >
            <a-select-option value="RESOURCE">资源</a-select-option>
            <a-select-option value="BEHAVIOR">行为</a-select-option>
            <a-select-option value="PUBLISH">发布</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="事件载荷" name="payload">
          <a-textarea
            v-model:value="eventForm.payload"
            placeholder="请输入事件载荷（JSON格式）"
            :rows="6"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// 响应式数据
const showCreateEventModal = ref(false);
const showEventDetailModal = ref(false);
const selectedEvent = ref<any>(null);

// 状态事件数据
const statusEvents = ref([
  {
    id: '1',
    type: 'STATUS_CHANGED',
    sourceId: props.resourceId,
    sourceType: 'RESOURCE',
    status: 'completed',
    timestamp: new Date(Date.now() - 3600000),
    correlationId: 'corr-001',
    payload: {
      oldStatus: 'DRAFT',
      newStatus: 'ACTIVE',
      reason: '资源初始化完成',
      operator: 'admin',
    },
  },
  {
    id: '2',
    type: 'CUSTOM_STATUS_CHANGED',
    sourceId: props.resourceId,
    sourceType: 'RESOURCE',
    status: 'pending',
    timestamp: new Date(Date.now() - 1800000),
    correlationId: 'corr-002',
    payload: {
      oldStatus: 'PENDING_REVIEW',
      newStatus: 'APPROVED',
      reason: '审核通过',
      operator: 'admin',
    },
  },
  {
    id: '3',
    type: 'AVAILABILITY_CHANGED',
    sourceId: props.resourceId,
    sourceType: 'RESOURCE',
    status: 'failed',
    timestamp: new Date(Date.now() - 900000),
    correlationId: 'corr-003',
    payload: {
      oldStatus: 'UNAVAILABLE',
      newStatus: 'AVAILABLE',
      reason: '系统维护完成',
      operator: 'system',
    },
  },
]);

// 表单数据
const eventFormRef = ref();
const eventForm = reactive({
  type: '',
  sourceType: '',
  payload: '',
});

// 表单验证规则
const eventRules = {
  type: [{ required: true, message: '请选择事件类型' }],
  sourceType: [{ required: true, message: '请选择源类型' }],
  payload: [{ required: true, message: '请输入事件载荷' }],
};

// 表格列定义
const columns = [
  { title: '事件ID', dataIndex: 'id', key: 'id', width: 120 },
  { title: '事件类型', key: 'type', width: 150 },
  { title: '源资源ID', dataIndex: 'sourceId', key: 'sourceId', width: 120 },
  { title: '源类型', dataIndex: 'sourceType', key: 'sourceType', width: 100 },
  { title: '状态', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'timestamp', key: 'timestamp', width: 180 },
  { title: '操作', key: 'action', width: 150 },
];

// 方法
const viewEventDetail = (record: any) => {
  selectedEvent.value = record;
  showEventDetailModal.value = true;
};

const executeEvent = async (record: any) => {
  try {
    record.status = 'completed';
    message.success('事件执行成功');
  } catch (error) {
    message.error('事件执行失败');
  }
};

const deleteEvent = async (id: string) => {
  try {
    statusEvents.value = statusEvents.value.filter((item) => item.id !== id);
    message.success('删除成功');
  } catch (error) {
    message.error('删除失败');
  }
};

const saveEvent = async () => {
  try {
    await eventFormRef.value.validate();

    let payload;
    try {
      payload = JSON.parse(eventForm.payload);
    } catch (error) {
      message.error('事件载荷格式错误，请使用有效的JSON格式');
      return;
    }

    const newEvent = {
      id: Date.now().toString(),
      type: eventForm.type,
      sourceId: props.resourceId,
      sourceType: eventForm.sourceType,
      status: 'pending',
      timestamp: new Date(),
      correlationId: `corr-${Date.now()}`,
      payload,
    };

    statusEvents.value.unshift(newEvent);
    message.success('事件创建成功');
    showCreateEventModal.value = false;
    resetEventForm();
  } catch (error) {
    message.error('创建事件失败');
  }
};

const resetEventForm = () => {
  eventFormRef.value?.resetFields();
  Object.assign(eventForm, {
    type: '',
    sourceType: '',
    payload: '',
  });
};

const refreshEvents = () => {
  message.success('事件列表已刷新');
};

const getEventTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    STATUS_CHANGED: 'blue',
    LIFECYCLE_CHANGED: 'green',
    AVAILABILITY_CHANGED: 'orange',
    VERSION_CHANGED: 'purple',
    CUSTOM_STATUS_CHANGED: 'cyan',
  };
  return colors[type] || 'default';
};

const getEventTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    STATUS_CHANGED: '状态变更',
    LIFECYCLE_CHANGED: '生命周期变更',
    AVAILABILITY_CHANGED: '可用性变更',
    VERSION_CHANGED: '版本变更',
    CUSTOM_STATUS_CHANGED: '自定义状态变更',
  };
  return labels[type] || type;
};

const getEventStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    pending: 'orange',
    completed: 'green',
    failed: 'red',
  };
  return colors[status] || 'default';
};

const getEventStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    pending: '待处理',
    completed: '已完成',
    failed: '失败',
  };
  return labels[status] || status;
};

const formatTime = (timestamp: Date) => {
  return timestamp.toLocaleString('zh-CN');
};

// 初始化
onMounted(() => {
  // 这里可以加载实际的状态事件数据
});
</script>

<style lang="less" scoped>
.status-event-panel {
  .ant-table {
    .ant-table-tbody > tr > td {
      padding: 8px;
    }
  }

  .event-detail {
    .event-payload {
      background: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-family: 'Courier New', monospace;
      font-size: 12px;
      overflow-x: auto;
    }
  }
}
</style>
